package com.demo.functions;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.functions.AbstractFunction;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author wangfengchen
 * 函数助手开发
 * 新建线程组，添加 BeanShell 取样器
 * 点最上方的工具，找到函数助手对话框，找到 MyDemo，然后输入值，点击生成，复制生成的函数字符串 ${__MyDemo(1,2)}，关闭函数助手，将字符串复制到 BeanShell 取样器中，点击执行
 */
public class Plus extends AbstractFunction {

  /**
   * 接收用户输入参数
   */
  private Object[] values;

  /**
   * 存储第一个和第二个参数
   */
  private CompoundVariable first, second;


  /**
   * 执行方法
   *
   * @param sampleResult
   * @param sampler
   * @return
   * @throws InvalidVariableException
   */
  @Override
  public String execute(SampleResult sampleResult, Sampler sampler) throws InvalidVariableException {
    System.out.println("execute run");
    first = (CompoundVariable) values[0];
    System.out.println("第一个参数是：" + new Integer(first.execute().trim()));
    second = (CompoundVariable) values[1];
    System.out.println("第二个参数是：" + new Integer(second.execute().trim()));
    int count = new Integer(first.execute().trim()) + new Integer(second.execute().trim());
    System.out.println("两数相加的和是：" + count);
    return String.valueOf(count);
  }

  /**
   * 设置参数，接收用户传递的参数
   *
   * @param collection
   * @throws InvalidVariableException
   */
  @Override
  public void setParameters(Collection<CompoundVariable> collection) throws InvalidVariableException {
    System.out.println("setParameters run");
    // 检查参数是否合法
    checkParameterCount(collection, 2);
    values = collection.toArray();
  }

  /**
   * 功能名称，注意前面必须带两个下划线，否则加载不到
   *
   * @return
   */
  @Override
  public String getReferenceKey() {
    System.out.println("getReferenceKey run");
    return "__MyDemo";
  }

  /**
   * 获取参数描述
   *
   * @return
   */
  @Override
  public List<String> getArgumentDesc() {
    System.out.println("getArgumentDesc run");
    List<String> descList = new ArrayList<>();
    descList.add("第一个数字");
    descList.add("第二个数字");
    return descList;
  }

}
